<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item prop="modelId">
        <el-input
          v-model="queryParams.modelId"
          placeholder="模型ID"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="projectCode">
        <el-input
          v-model="queryParams.projectCode"
          placeholder="项目编码"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item prop="projectName">
        <el-input
          v-model="queryParams.projectName"
          placeholder="项目名称"
          clearable
          size="small"
          style="width: 180px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始更新时间"
          end-placeholder="结束更新时间"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="small" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="small" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="small"
          @click="handleAdd"
          v-hasPermi="['buz:model:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="small"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['buz:model:remove']"
        >删除
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['buz:model:edit']"
        >编辑</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-edit"
          size="small"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['buz:model:edit']"
        >查看</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          icon="el-icon-download"
          size="small"
          @click="handleExport"
          v-hasPermi="['buz:model:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="modelList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="模型ID" align="center" prop="modelId"/>
      <el-table-column label="模型名称" align="center" prop="modelName"/>
      <el-table-column label="模型存储路径" align="center" prop="modelUrl"/>
      <el-table-column align="center" width="80" prop="thumbUrl" label="图片">
        <template scope="scope">
          <el-popover placement="right" title="" trigger="hover">
            <img :src="scope.row.thumbUrl" style="height: 400px;width: 500px">
            <img slot="reference" :src="scope.row.thumbUrl" :alt="scope.row.thumbUrl" style="max-height: 50px;max-width: 130px">
          </el-popover>
        </template>
      </el-table-column>
      <el-table-column label="模型描述" align="center" prop="modelDes"/>
      <el-table-column label="更新时间" align="center" prop="createTime" width="160">
                <template slot-scope="scope">
                <span>{{ parseTime(scope.row.createTime) }}</span>
                </template>
            </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['buz:model:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleBind(scope.row.modelId)"
            v-hasPermi="['buz:model:bind']"
          >绑定
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模型对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-row :gutter="15">
        <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="100px">
          <el-col :span="16">
            <el-form-item label="模型名称" prop="modelName">
              <el-input v-model="form.modelName" :maxlength="50" clearable :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="模型上传" prop="url" required>
              <el-upload ref="url" :file-list="modelFileList" :action="uploadAction" :on-success="uploadModelAction"
                         :before-upload="ModelBeforeUpload" :headers="tokenHeaders" v-hasPermi="['buz:model:upload']">
                <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="户型图上传" prop="thumbUrl" required>
              <el-upload ref="thumbUrl" :file-list="imgList" :action="uploadAction" :on-success="uploadImgAction"
                         :before-upload="imgBeforeUpload" :headers="tokenHeaders" list-type="picture" accept="image/*" v-hasPermi="['buz:model:upload']">
                <el-button size="small" type="primary" icon="el-icon-upload">点击上传</el-button>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 绑定房屋操作窗口 -->
    <el-dialog :title="title" :visible.sync="bindOpen" width="500px" append-to-body>
      <el-row :gutter="15">
        <el-form ref="bindForm" :model="bindForm" :rules="rules" size="medium" label-width="100px">
          <el-col :span="16">
            <el-form-item label="模型名称" prop="modelName">
              <el-input v-model="bindForm.modelName" :maxlength="50" disabled :style="{width: '100%'}">
              </el-input>
            </el-form-item>
          </el-col>
          <el-col :span="16">
            <el-form-item label="房屋选择" prop="deptIds">
              <el-tree
                :data="deptOptions"
                :props="defaultProps"
                :expand-on-click-node="true"
                show-checkbox
                node-key="id"
                ref="dept"
              />
<!--              :filter-node-method="filterNode"-->
<!--              @node-click="handleNodeClick"-->
            </el-form-item>
          </el-col>
        </el-form>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitBinding">确 定</el-button>
        <el-button @click="cancelBind">取 消</el-button>
      </div>
    </el-dialog>


  </div>
</template>

<script>
import {listModel, getModel, addModel, delModel, updateModel, bindModel} from "@/api/buz/model";
import Cookies from 'js-cookie';
import { treeselect } from "@/api/system/dept";

export default {
  name: "Model",
  // components: { Treeselect },
  data() {
    return {
       // 日期范围
      dateRange: [],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 部门树选项
      deptOptions: undefined,
      // 模型表格数据
      modelList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 是否显示绑定弹出层
      bindOpen : false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        modelName: null,
      },
      // 添加或修改模型表单参数
      form: {},
      // 绑定模型表单参数
      bindForm : {
        modelId : undefined,
        modelName : undefined,
        deptIds : undefined
      },
      // 表单校验
      rules: {
        modelName: [{
          required: true,
          message: '模型名称不能为空',
          trigger: 'blur'
        }],
      },
      modelFileList : [],
      imgList : [],
      uploadAction : "http://localhost:21000/dev-api/buz/model/upload",
      tokenHeaders : {
                        "Authorization" : "Bearer " + Cookies.get('Admin-Token'),
                        "device" : "web"
                     },
      defaultProps: {
        children: "children",
        label: "label"
      }
    };
  },
  created() {
    this.getList();
    this.getTreeselect();
  },
  methods: {
    /** 查询模型列表 */
    getList() {
      this.loading = true;
      listModel(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.modelList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        modelName: null,
        url: null,
        thumbUrl: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange=[];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.modelId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加模型";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const modelId = row.modelId || this.ids
      getModel(modelId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改模型";
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.modelId) {
            updateModel(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }
            });
          } else {
            addModel(this.form).then(response => {
              if (response.code === 200) {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }
            });
          }
        }
      });
    },
    /** 绑定按钮操作 */
    handleBind(modelId) {
      //  显示绑定窗口
      getModel(modelId).then(response => {
        this.bindForm.modelName = response.data.modelName;
        this.bindForm.modelId = response.data.modelId;
        this.bindOpen = true;
        this.title = "绑定房屋";
      });
    },
    ModelBeforeUpload(file){
      let isRightSize = file.size / 1024 / 1024 /1024 < 3;
      if (!isRightSize) {
        this.$message.error('文件大小超过 3G');
      }
      return isRightSize;
    },
    imgBeforeUpload(file){
      let isRightSize = file.size / 1024 / 1024 < 10;
      if (!isRightSize) {
        this.$message.error('文件大小超过 10MB');
      }
      let isAccept = new RegExp('image/*').test(file.type);
      if (!isAccept) {
        this.$message.error('应该选择image/*类型的文件');
      }
      return isRightSize && isAccept;
    },
    uploadModelAction(response){
        if (response.code === 200) {
          this.form.url = response.data.url;
        }
    },
    uploadImgAction(response){
      if (response.code === 200) {
        this.form.thumbUrl = response.data.url;
      }
    },
    filterNode(value, data) {
      if (!value) return true;
      return data.label.indexOf(value) !== -1;
    },
    handleNodeClick(data) {
      this.queryParams.deptId = data.id;
      this.getList();
    },
    submitBinding(){
      this.$refs["bindForm"].validate(valid => {
        if (valid) {
          this.bindForm.deptIds = this.$refs.dept.getCheckedKeys();
          bindModel(this.bindForm).then(response => {
            if (response.code === 200) {
              this.msgSuccess("绑定成功");
              this.bindOpen = false;
            }
          });
        }
      });
    },
    // 所有部门节点数据
    getDeptAllCheckedKeys() {
      // 目前被选中的部门节点
      let checkedKeys = this.$refs.dept.getHalfCheckedKeys();
      // 半选中的部门节点
      let halfCheckedKeys = this.$refs.dept.getCheckedKeys();
      checkedKeys.unshift.apply(checkedKeys, halfCheckedKeys);
      return checkedKeys;
    },
    bindReset(){
      this.form = {
        modelName: null,
        modelId : null,
        deptIds : []
      };
      this.resetForm("bindForm");
    },
    cancelBind(){
      this.bindOpen = false;
      this.bindReset();
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const modelIds = row.modelId || this.ids;
      this.$confirm('是否确认删除模型编号为"' + modelIds + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delModel(modelIds);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(function () {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('buz/device/export', {
        ...this.queryParams
      }, `buz_device.xlsx`)
    }
  }
};
</script>
